package pers.cj.pdos.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;

import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.Custom;
import pers.cj.pdos.entity.Goods;
import pers.cj.pdos.entity.House;
import pers.cj.pdos.service.ICustomService;
import pers.cj.pdos.service.IUserService;
import pers.cj.pdos.utils.DataUtil;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.DataMsg;
import pers.cj.pdos.vo.CustomVo;
import pers.cj.pdos.vo.ProviderVo;
import pers.cj.pdos.vo.UserVo;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/custom")
public class CustomController extends BaseController {
    @Autowired
    ICustomService customService;
    @Autowired
    IUserService userService;

    @RequestMapping("/custom")
    @RequiresPermissions("custom:query")
    public String customType() {
        return "/custom/custom";
    }

    @RequestMapping("/customNew")
    @RequiresPermissions("custom:insert")
    public String customNew() {
        return "/custom/customNew";
    }

    @RequestMapping("/customEdit")
    @RequiresPermissions("custom:insert")
    public String customEdit(Model model, String id) {
        model.addAttribute("id",id);
        return "/custom/customEdit";
    }

    @ResponseBody
    @RequestMapping("/custom/getList")
    public ResponseList getList(int page,
                                int limit,
                                String search,
                                String status,
                                String customTypeId,
                                String no,
                                String name,
                                String unitTel,
                                String phone,
                                String contacts,
                                String remark,
                                String userId) {
        Company company = getCompany();

        UserVo userVo = getLoginUserVo();

        List<CustomVo> customVoList = customService.listVoPage(company.getId(),
                page,
                limit,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                customTypeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(unitTel),
                Utils.genLikeData(phone),
                Utils.genLikeData(contacts),
                Utils.genLikeData(remark),
                PdosUtils.getViewCustomStoreId(userVo,null),
                userId);
        long count = customService.count(company.getId(),
                Utils.genInteger(status),
                Utils.genLikeData(search),
                customTypeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(unitTel),
                Utils.genLikeData(phone),
                Utils.genLikeData(contacts),
                Utils.genLikeData(remark),
                PdosUtils.getViewCustomStoreId(userVo,null),
                userId);
        return ResponseList.success(count,customVoList);
    }

    @ResponseBody
    @RequiresPermissions("custom:insert")
    @RequestMapping("/custom/add")
    public ResponseEntity add(@RequestBody Custom custom) {
        if (Utils.isEmpty(custom.getName())){
            return ResponseEntity.fail("客户名称不能为空");
        }
        if (Utils.isEmpty(custom.getNo())){
            return ResponseEntity.fail("客户编号不能为空");
        }
        if (Utils.isEmpty(custom.getStoreId())){
            return ResponseEntity.fail("门店不能为空");
        }
        if (Utils.isEmpty(custom.getCustomTypeId())){
            return ResponseEntity.fail("分类不能为空");
        }

        Company company = getCompany();

        if (customService.checkName(company.getId(), custom.getName())) {
            return ResponseEntity.fail("客户名称已存在");
        }

        if (customService.checkNo(company.getId(), custom.getNo())) {
            return ResponseEntity.fail("客户编号已存在");
        }

        if(!userService.exist(custom.getUserId())) {
            custom.setUserId("");
        }

        DataUtil.processEntity(company, custom);

        if (custom.getInitAmt() == null) {
            custom.setInitAmt(new BigDecimal(0));
        }
        customService.save(custom);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("custom:insert")
    @RequestMapping("/custom/update")
    public ResponseEntity update(@RequestBody Custom custom) {
        if (Utils.isEmpty(custom.getName())){
            return ResponseEntity.fail("客户名称不能为空");
        }
        if (Utils.isEmpty(custom.getNo())){
            return ResponseEntity.fail("客户编号不能为空");
        }
        if (Utils.isEmpty(custom.getStoreId())){
            return ResponseEntity.fail("门店不能为空");
        }
        if (Utils.isEmpty(custom.getCustomTypeId())){
            return ResponseEntity.fail("分类不能为空");
        }

        Company company = getCompany();
        Custom old = customService.getById(custom.getId());
        if (!old.getName().equals(custom.getName()) && customService.checkName(company.getId(), custom.getName())) {
            return ResponseEntity.fail("客户名称已存在");
        }

        if (!old.getNo().equals(custom.getNo()) && customService.checkNo(company.getId(), custom.getNo())) {
            return ResponseEntity.fail("客户编号已存在");
        }

        DataUtil.processEntity(false, company, custom);
        if (custom.getInitAmt() == null) {
            custom.setInitAmt(new BigDecimal(0));
        }
        customService.update(custom);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("custom:insert")
    @RequestMapping("/custom/delete")
    public ResponseEntity delete(@RequestBody Custom custom) {
        try{
            customService.removeById(custom.getId());
            return ResponseEntity.success();
        } catch (Exception e) {
            return ResponseEntity.fail("已被使用无法删除");
        }
    }

    @ResponseBody
    @RequiresPermissions("custom:insert")
    @RequestMapping("/custom/batchChangeCustomType")
    public ResponseEntity batchChangeCustomType(String customTypeId, @RequestBody List<Custom> list) {
        customService.batchChangeCustomType(customTypeId, list);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("custom:insert")
    @RequestMapping("/custom/batchDelete")
    public ResponseData batchDelete(@RequestBody List<Custom> list) {

        //判断哪些商品被单据引用了
        Map<String,Long> map = customService.check(list);
        List<DataMsg> notDeleteList = new ArrayList<>();
        List<Custom> deleteList = new ArrayList<>();

        Collection<Custom> collection = customService.listByIds(DataUtil.genIds(list));
        for (Custom custom:collection){
            if(map.containsKey(custom.getId()) && map.get(custom.getId()) > 0) {
                //当该商品的被单据引用，则从列表中剔除该商品
                notDeleteList.add(new DataMsg(custom,"被业务单据引用"));
                continue;
            }
            deleteList.add(custom);
        }


        ResponseData responseData;
        if (notDeleteList.size() > 0) {
            responseData = new ResponseData();
            responseData.setCode(3);
            responseData.setMsg("部分商品被单据引用");
            responseData.setData(notDeleteList);
        } else {
            responseData = ResponseData.success(null);
        }

        if (Utils.isEmpty(deleteList)){
            return responseData;
        }

        try {
            customService.deleteBatch(deleteList);
            return responseData;
        } catch (Exception e){
            return ResponseData.fail("删除失败");
        }
    }

    @ResponseBody
    @RequestMapping("/custom/checkName")
    public ResponseEntity checkName(String name) throws UnsupportedEncodingException {
        Company company = getCompany();
        boolean exist = customService.checkName(company.getId(), URLDecoder.decode(name,"UTF-8"));

        return exist ?  new ResponseEntity(1,"已被使用") : new ResponseEntity(2,"未被使用");
    }

    @ResponseBody
    @RequestMapping("/custom/getById")
    public ResponseData getById(String id) {
        if (Utils.isEmpty(id)) {
            return ResponseData.fail("id不能为空");
        }
        Custom custom = customService.getById(id);
        if (custom == null ) {
            return ResponseData.fail("未找到客户");
        }
        return ResponseData.success(custom);
    }

    @ResponseBody
    @RequestMapping("/custom/getAll")
    public ResponseData getAll() {
        return ResponseData.success(customService.listVo(getCompany().getId()));
    }

    @ResponseBody
    @RequestMapping("/custom/getDefault")
    public ResponseData getDefault() {
        Custom custom = customService.getDefault(getLoginUserVo().getStoreId());
        return custom==null ? ResponseData.fail("暂无默认客户"): ResponseData.success(custom);
    }
}
